//
//  GrowthTableViewCell.swift
//  BellManage
//
//  Created by Bestsch on 16/3/31.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class GrowthTableViewCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate {
    
    var bgView, photoBgView: UIView!
    var titleLabel,timeLabel,contentLabel,markLabel: UILabel!
    var markImg: UIImageView!
    var oneImage: PicProgressView!
    var photoCollectionView: UICollectionView!
    var userTX: UIImageView!
    var userName: UILabel!
    var share: UIImageView!
    
    var dic: JSON!
    var apiUrl: String!
    
    let collectionIdentifier = "PicCollectionViewCellIdentifier"
    let imageArray = NSMutableArray()
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    init(dictionary: JSON, apiUrl: String!, reuseIdentifier: String?) {
        self.apiUrl = apiUrl
        self.dic = dictionary
        super.init(style: UITableViewCellStyle.default, reuseIdentifier: reuseIdentifier)
        setUp()
    }
    
    /**
     初始化设置各种控件
     */
    func setUp() {
        
        bgView = UIView.init(frame: CGRect.zero)
        bgView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        
        userTX = UIImageView.init(frame: CGRect.zero)
        
        userName = UILabel.init(frame: CGRect.zero)
        userName.textColor = UIColor.darkGray
        userName.textAlignment = NSTextAlignment.left
        
        timeLabel = UILabel.init(frame: CGRect.zero)
        timeLabel.font = UIFont.systemFont(ofSize: 14)
        timeLabel.textColor = UIColor.darkText
        timeLabel.textAlignment = NSTextAlignment.right
        
        titleLabel = UILabel.init(frame: CGRect.zero)
        titleLabel.numberOfLines = 0
        titleLabel.font = UIFont.systemFont(ofSize: 16)
        titleLabel.textColor = UIColor.black
        titleLabel.textAlignment = NSTextAlignment.left
        
        contentLabel = UILabel.init(frame: CGRect.zero)
        contentLabel.font = UIFont.systemFont(ofSize: 14)
        contentLabel.numberOfLines = 0
        contentLabel.textColor = UIColor.darkText
        
        markLabel = UILabel.init(frame: CGRect.zero)
        markLabel.font = UIFont.systemFont(ofSize: 14)
        markLabel.textColor = barColor
        
        markImg = UIImageView.init(frame: CGRect.zero)
        
        photoCollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: photoFlowLayout.init())
        photoCollectionView.backgroundColor = UIColor.white
        photoCollectionView.register(PicCollectionViewCell.self, forCellWithReuseIdentifier: collectionIdentifier)
        photoCollectionView.scrollsToTop = true
        photoCollectionView.delegate = self
        photoCollectionView.dataSource = self
        
        photoBgView = UIView.init(frame: CGRect.zero)
        photoBgView.backgroundColor = UIColor.white
        
        
        
        oneImage = PicProgressView.init(frame: CGRect.zero)
        oneImage.isUserInteractionEnabled = true
        let showImage = UITapGestureRecognizer.init(target: self, action: #selector(GrowthTableViewCell.showImage))
        oneImage.addGestureRecognizer(showImage)
        
        share = UIImageView.init(frame: CGRect.zero)
        share.image = UIImage.init(named: "sharehui")
        share.isUserInteractionEnabled = true
        let shareClick = UITapGestureRecognizer.init(target: self, action: #selector(GrowthTableViewCell.shareNotice))
        share.addGestureRecognizer(shareClick)
        
        
        
        self.contentView.addSubview(bgView)
        self.contentView.addSubview(userTX)
        self.contentView.addSubview(userName)
        self.contentView.addSubview(photoBgView)
        self.contentView.addSubview(titleLabel)
        self.contentView.addSubview(timeLabel)
        self.contentView.addSubview(contentLabel)
        self.contentView.addSubview(markImg)
        self.contentView.addSubview(markLabel)
        #if EDUMANAGE || HSEDUMANAGE || TXEDUMANAGE
            self.contentView.addSubview(share)
        #endif
        
        var title = dic["title"].stringValue
        var content = dic["contents"].stringValue
        
        title = title.removingPercentEncoding!
        content = content.removingPercentEncoding!
        
        let imageUrl = dic["imgurl"].stringValue
        let time = dic["editdate"].stringValue
        let markType = dic["stype"].stringValue
        let name = dic["stuname"].stringValue
        let classname = dic["classname"].stringValue
        var photo = ""//头像
        photo = photo.replacingOccurrences(of: "../..", with: "").replacingOccurrences(of: "../", with: "/view/")
        
        userTX.sd_setImage(with: URL.init(string: server + photo), placeholderImage: UIImage.init(named: "touxiangm"))
        
        let str = name + " " + classname
        let st2 = NSMutableAttributedString.init(string: str)
        st2.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16), range: NSMakeRange(0, name.characters.count))
        st2.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(name.characters.count, st2.length - name.characters.count))
        userName.attributedText = st2
        
        timeLabel.text = getTimeSinceNow(time).replacingOccurrences(of: ".", with: "")
        titleLabel.text = title
        contentLabel.text = content
        markImg.image = UIImage.init(named: "bq2")
        markLabel.text = markType
        
        var height: CGFloat = 0.0
        if imageUrl.characters.count == 0 || imageUrl == "alse"{
            photoBgView.removeFromSuperview()
            height = 0.0
        }else {
            
            let array = imageUrl.components(separatedBy: "|") as NSArray
            
            if array.count == 1 {
                self.contentView.addSubview(oneImage)
                
                let photo = imageUrl.replacingOccurrences(of: "../..", with: "")
                var imageurl = server + priImg + photo + "&width=400&mode=W"
                let user = getUserPojo()
                if self.apiUrl.characters.count != 0 {
                    imageurl = imageurl.replacingOccurrences(of: server, with: user.doname).replacingOccurrences(of: "", with: "")
                }
                oneImage.imageUrl = imageurl
            }else {
                self.contentView.addSubview(photoCollectionView)
                imageArray.addObjects(from: array as [AnyObject])
            }
            height = getPhotoCollectionHeight(array)
        }
        /// 头像，间隔，上下间隔，时间，图片等，内容
        let cellHeight: CGFloat = 20.0 + 50.0  + 30.0 + height + getLabelHeight(title, font: UIFont.systemFont(ofSize: 16) , wigth: screenW - 40) + getLabelHeight(content, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 40) + 5
        
        bgView.frame = CGRect(x: 10, y: 10, width: screenW - 20, height: cellHeight - 20)
        bgView.layer.cornerRadius = 4;
        bgView.layer.shadowOffset = CGSize(width: 0, height: 1);  // 设置阴影的偏移量
        bgView.layer.shadowRadius = 2.0;  // 设置阴影的半径
        bgView.layer.shadowColor = UIColor.lightGray.cgColor; // 设置阴影的颜色为黑色
        bgView.layer.shadowOpacity = 0.8; // 设置阴影的不透明度
        
        userTX.frame = CGRect(x: 20, y: 20, width: 30, height: 30)
        userTX.layer.cornerRadius = 15
        
        userName.frame = CGRect(x: userTX.frame.maxY+10, y: 20, width: screenW/2, height: 30)
        
        timeLabel.frame = CGRect(x: screenW/2, y: 20, width: screenW/2 - 20, height: 30)
        
        
        titleLabel.frame = CGRect(x: 20, y: userTX.frame.maxY+5, width: screenW - 40, height: getLabelHeight(title, font: UIFont.systemFont(ofSize: 16) , wigth: screenW - 40));
        
        photoBgView.frame = CGRect(x: bgView.frame.minX, y: titleLabel.frame.maxY + 5, width: bgView.frame.width, height: height)
        oneImage.frame = CGRect(x: photoBgView.frame.minX+5, y: photoBgView.frame.minY+5, width: photoBgView.frame.width-10, height: photoBgView.frame.height-10);
        photoCollectionView.frame = CGRect(x: photoBgView.frame.minX+5, y: photoBgView.frame.minY+5, width: photoBgView.frame.width-10, height: self.photoBgView.frame.height-10);
        
        contentLabel.frame = CGRect(x: bgView.frame.minX + 10, y: photoBgView.frame.maxY+5, width: screenW - 40, height: getLabelHeight(content, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 40))
        
        //类型
        markImg.frame = CGRect(x: 20, y: contentLabel.frame.maxY+6, width: 16.5, height: 17)
        markLabel.frame = CGRect(x: markImg.frame.maxX+5, y: contentLabel.frame.maxY, width: 80, height: 30)
        share.frame = CGRect(x: bgView.frame.maxX - 30, y: contentLabel.frame.maxY+5, width: 18, height: 20)
        
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: PicCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionIdentifier, for: indexPath) as! PicCollectionViewCell
        cell.backgroundColor = UIColor.white
        var photo = imageArray.object(at: (indexPath as NSIndexPath).row) as! String
        photo = photo.replacingOccurrences(of: "../..", with: "")
        var imageurl = server + priImg + photo + "&width=300&mode=W"
        let user = getUserPojo()
        if self.apiUrl.characters.count != 0 {
            imageurl = imageurl.replacingOccurrences(of: server, with: user.doname).replacingOccurrences(of: "", with: "")
        }
        cell.imageUrl = imageurl
        return cell;
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let imageUrl = dic["imgurl"].stringValue
        let index = String((indexPath as NSIndexPath).row)
        NotificationCenter.default.post(name: Notification.Name(rawValue: "showBigImage"), object: nil, userInfo: ["url" : imageUrl, "index" : index])
        
    }
    /**
     显示大图
     */
    func showImage() {
        let imageUrl = dic["imgurl"].stringValue
        let index = "0"
        NotificationCenter.default.post(name: Notification.Name(rawValue: "showBigImage"), object: nil, userInfo: ["url" : imageUrl, "index" : index])
    }
    /**
     分享
     */
    func shareNotice(){
        let serid = self.dic["serid"].stringValue
        var title = self.dic["title"].stringValue
        title = title.removingPercentEncoding!
        let stuname = self.dic["stuname"].stringValue
        let imageUrl = dic["imgurl"].stringValue
        NotificationCenter.default.post(name: Notification.Name(rawValue: "shareGrowNotification"), object: nil, userInfo: ["serid" : serid, "title" : title, "stuname" : stuname, "imageUrl" : imageUrl])
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
}
